#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import tornado.web
import datetime
import threading

from controls import mc
from config import etc
from utils import log
from utils import util
from controls import data_city_base_mysql


def set_city_item_to_mc(pfx, key, item):
    return mc.set_item(pfx, key, item)


def get_city_all():
    try:
        city = 'city'
        city_item = mc.get_item(city, 0)
        if city_item is None:
            item = data_city_base_mysql.get_city_all()
            t = threading.Thread(target=set_city_item_to_mc, args=(city, 0, item))
            t.start()
            return item
        else:
            return util.decode(city_item)

    except Exception, e:
        log.exp(e)
        return False


def add_city_base_item(item):
    res_mc = mc.set_item('city', 0, item)
    if not res_mc:
        return False
    for one in range(0, len(item)):
        res_db = data_city_base_mysql.add_city_base_item(item[one])
        if not res_db:
            mc.set_item('city', 0, None)
            return False

    return True


if __name__ == '__main__':
    print get_city_all()
    item = [{'pos_x': 100.0, 'pos_y': 120.0, 'name': u'guilin', 'provid': 0L, 'cityid': 1L, 'cname': u'\u6842\u6797',
             'version': 1L},
            {'pos_x': 100.0, 'pos_y': 120.0, 'name': u'qingdao', 'provid': 0L, 'cityid': 2L, 'cname': u'\u9752\u5c9b',
             'version': 1L}]
    print add_city_base_item(item)
